import { useRef, useState } from 'react';

import { allGet } from '@/services/pc';
import storage from '@/utils/storage';
import { TOKEN } from '@/common/const';

export default () => {
  const [order, setOrderData] = useState<any>({});
  const [loading, setLoading] = useState<boolean>(false);
  const [unPay, setUnPay] = useState<boolean>(false);
  const isInit = useRef(false);
  // 获取购买订单
  const getOrder = async () => {
    const token = storage.get(TOKEN);
    if (!token?.value) return;
    setLoading(true);
    const response = await allGet({
      params: { mod: 'enroll', do: 'all', version: 'pc1.0' },
    });
    const data = {
      ...(response?.data ?? {}),
    };
    // 判断是否有未支付的订单
    if (response?.data?.list?.some?.((item) => Number(item?.data?.status) <= 0)) {
      setUnPay(true);
    }
    isInit.current = true;
    setOrderData(data);
    setLoading(false);
  };

  const setOrder = (data: Record<string, any>) => {
    setOrderData({
      ...order,
      ...data,
    });
  };

  return {
    loading,
    order,
    unPay,
    getOrder,
    setOrder,
    isInit,
  };
};
